import React from 'react';
import {messages, deepCopy} from "share/common";
import 'styles/enterprise-manage/person-manage/person-detail/person-detail-components/common-consumer.scss';
import {Button, Form, Select, Checkbox, Row, Col, Icon, Input, Modal, InputNumber, message, Popover} from 'antd';
import Chooser from 'components/chooser';
import PDService from 'containers/enterprise-manage/person-manage/person-detail/person-detail.service';
const FormItem = Form.Item;
const Option = Select.Option;
const formItemLayout = {
  labelCol: {span: 7},
  wrapperCol: {span: 16}
};
const scopeOptionMap = {
  domesticFlight: messages('basic-5.key848')/*国内机票*/,
  internationalFlight: messages('basic-5.key849')/*国际机票*/,
  domesticHotel: messages('basic-5.key850')/*国内酒店*/,
  internationalHotel: messages('basic-5.key851')/*国际酒店*/,
  car: messages('basic-5.key852')/*用车*/,
  train: messages('basic-5.key853')/*火车票*/,
  reschedule: messages('basic-5.key854')/*改签*/,
  refund: messages('basic-5.key855')/*退票*/,
};
const scopeOptions = ['domesticFlight', 'internationalFlight', 'domesticHotel', 'internationalHotel', 'car', 'train',
  'reschedule', 'refund'];

class CommonConsumer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      ctripList: [],//携程子账户
      helpOthersBookCodeList: [],//代订类型
      bookTheScopeCodeList: [],//代订范围
      vendorObj: {},
      prepareObj: {},
      currentIndex: 0,
      visible: false,
      isNew: false,
      saveLoading: false,

    }
  };

  componentDidMount() {
    const vendorObj = this.props.data;
    if(vendorObj) {
      this.initVendorObj(vendorObj);
    }
    this.getValueList();
  }

  initVendorObj = (vendorObj) => {
    (vendorObj.commonAgencyAuthDTOS || []).forEach(auth => {
      if(auth.commonAgencyAuthDetailDTOS && auth.commonAgencyAuthDetailDTOS.length){
        let arr = [{checkSequence: 1},{checkSequence: 2},{checkSequence: 3},{checkSequence: 4}];
        arr.forEach((item, index) => {
          let result = auth.commonAgencyAuthDetailDTOS.find(inside =>  inside.checkSequence === item.checkSequence);
          if(result){arr[index] = result;}
        });
        auth.commonAgencyAuthDetailDTOS = arr;
      }else{
        auth.commonAgencyAuthDetailDTOS = [{checkSequence: 1},{checkSequence: 2},{checkSequence: 3},{checkSequence: 4}];
      }
    });
    this.setState({
      vendorObj,
    });
  };

  //获取需要的值列表
  getValueList = () => {
    //获取携程子账户
    Promise.all([
      this.getSystemValueList(1003), //表单详情
      this.getSystemValueList(2217),             //申请人详情
      this.getSystemValueList(2218)     //岗位信息
    ]).then(res => {
      this.setState({
        ctripList: res[0].data.values,
        helpOthersBookCodeList: res[1].data.values,
        bookTheScopeCodeList: res[2].data.values,
      })
    }).catch(() => {
    });
  };

  //渲染携程子账户
  renderCtripAccountOption = (data) => {
    if (data && data.length) {
      return data.map((item) => {
        return <Option value={item.value} key={item.value}>{item.messageKey}</Option>
      })
    } else {
      return (<Option value={""} key={1}>{""}</Option>)
    }
  };

  onCheckBoxChange = (e) => {
    let {vendorObj} = this.state;
    vendorObj.nonEmployeeIncluded = e.target.checked;
    this.setState({
      vendorObj,
    });
  };

  handleEdit = (e, item, index) => {
    let {prepareObj} = this.state;
    prepareObj.authSequence = item.authSequence;
    Object.keys(item).forEach(key => {
      if(scopeOptions.includes(key)){
        prepareObj[key] = item[key];
      }
    });
    this.setState({
      currentIndex: index,
      prepareObj,
      isNew: false,
      visible: true
    })
  };

  onValueChange = (value) => {
    let {prepareObj} = this.state;
    prepareObj.authSequence = value;
    this.setState({
      prepareObj,
    });
  };

  onAuthScopeChange = (e, attr) => {
    let {vendorObj, prepareObj} = this.state;
    prepareObj[attr] = e.target.checked;
    this.setState({
      vendorObj,
    });
  };

  onModalOk = () => {
    let {vendorObj, currentIndex, prepareObj, isNew} = this.state;
    if(!prepareObj.authSequence){
      message.error(messages('basic-5.key856')/*请输入授权序号*/);
      return
    }
    if(vendorObj.commonAgencyAuthDTOS && vendorObj.commonAgencyAuthDTOS.length){
      let bool = vendorObj.commonAgencyAuthDTOS.find((item, index) =>
        isNew ? item.authSequence === prepareObj.authSequence : index !== currentIndex && item.authSequence === prepareObj.authSequence
      );
      if(bool){
        message.error(messages('basic-5.key857')/*授权序号重复，请重新编辑序号*/);
        return
      }
    }
    let allow = Object.keys(prepareObj).find(item => prepareObj[item] === true);
    if(!allow){
      message.error(messages('basic-5.key858')/*授权服务范围不能为空*/);
      return
    }
    if(!vendorObj.commonAgencyAuthDTOS || !vendorObj.commonAgencyAuthDTOS.length){
      vendorObj.commonAgencyAuthDTOS = [prepareObj];
      vendorObj.commonAgencyAuthDTOS[0].commonAgencyAuthDetailDTOS = [{checkSequence: 1},{checkSequence: 2},{checkSequence: 3},{checkSequence: 4}];

    }else{
      if(isNew){
        vendorObj.commonAgencyAuthDTOS.push(prepareObj);
        vendorObj.commonAgencyAuthDTOS[vendorObj.commonAgencyAuthDTOS.length - 1].commonAgencyAuthDetailDTOS =
          [{checkSequence: 1},{checkSequence: 2},{checkSequence: 3},{checkSequence: 4}];
      }else{
        let obj = vendorObj.commonAgencyAuthDTOS[currentIndex];
        vendorObj.commonAgencyAuthDTOS[currentIndex] = Object.assign(obj, prepareObj);
      }
    }
    this.setState({
      visible: false,
      vendorObj,
      prepareObj: {},
    })
  };

  handleDelete = (e, item, index) => {
    Modal.confirm({
      content: messages('basic-5.key859')/*确认要删除该授权服务范围吗？*/,
      onOk: () => this.deleteAuthScope(item, index)
    })
  };
  
  deleteAuthScope = (item, index) => {
    let {vendorObj} = this.state;
    if(item.id){
      vendorObj.commonAgencyAuthDTOS[index].deleteLoading = true;
      this.setState({
        vendorObj,
      });
      PDService.deleteAuthScope(item.id).then(res => {
        vendorObj.commonAgencyAuthDTOS.splice(index, 1);
        this.setState({
          vendorObj,
        });
      }).catch(err => {
        message.error(messages('finance-4.key263')/*删除失败*/);
      })
    }else{
      vendorObj.commonAgencyAuthDTOS.splice(index, 1);
      this.setState({
        vendorObj,
      });
    }
  };

  saveCommonConsumer = () => {
    let {vendorObj} = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        let {bookTheScopeCode, helpOthersBookCode, subAccountCode, positionShield, confirmPassword} = values;
        vendorObj.bookTheScopeCode = bookTheScopeCode ? bookTheScopeCode.key : "";
        vendorObj.bookTheScopeName = bookTheScopeCode ? bookTheScopeCode.label : "";
        vendorObj.helpOthersBookCode = helpOthersBookCode ? helpOthersBookCode.key : "";
        vendorObj.helpOthersBookName = helpOthersBookCode ? helpOthersBookCode.label : "";
        vendorObj.subAccountCode = subAccountCode ? subAccountCode.key : "";
        vendorObj.subAccountName = subAccountCode ? subAccountCode.label : "";
        vendorObj.positionShield = positionShield;
        vendorObj.confirmPassword = confirmPassword;
        let params = deepCopy(vendorObj);
        if(!params.userOID){
          params.userOID = this.props.userOID;
        }
        if(params.commonAgencyAuthDTOS && params.commonAgencyAuthDTOS.length){
          params.commonAgencyAuthDTOS.forEach(item => {
            if(item.commonAgencyAuthDetailDTOS && item.commonAgencyAuthDetailDTOS.length){
              item.commonAgencyAuthDetailDTOS.forEach((sub, ins) => {
                sub.checkSequence = sub.checkSequence || ins + 1;
                delete sub.confirmUser;
                delete sub.confirmCCUser;
              })
            }
          })
        }
        this.setState({saveLoading: true,});
        PDService.addCommonConsumer(params)
          .then(res=>{
            this.reset();
            this.props.cancelEdit();
            this.setState({saveLoading: false,});
          }).catch(err => {
            this.setState({saveLoading: false,});
        })
      }
    });
  };

  reset = () => {
    PDService.getAllKindsOfCards(this.props.userOID).then(res => {
      if(res && res.data && res.data.commonAgencyDTO) {
        this.initVendorObj(res.data.commonAgencyDTO);
      }else {
        this.setState({
          vendorObj: {},
        })
      }
    }).catch(err => {

    })
  };

  checkOptionDisabled = (opt) => {
    let {vendorObj, currentIndex, isNew} = this.state;
    let bool = false;
    if(vendorObj.commonAgencyAuthDTOS && vendorObj.commonAgencyAuthDTOS.length){
      vendorObj.commonAgencyAuthDTOS.forEach((item, index) => {
        if(isNew){
          if(item[opt]){
            bool = true;
          }
        }else {
          if(index !== currentIndex && item[opt]) {
            bool = true;
          }
        }
      });
    }
    return bool;
  };

  handleNew = () => {
    let {prepareObj, vendorObj} = this.state;
    if(vendorObj.commonAgencyAuthDTOS && vendorObj.commonAgencyAuthDTOS.length >=8){
      message.error(messages('basic-5.key860')/*授权服务范围最多允许添加8个*/);
      return
    }
    this.setState({
      isNew: true,
    }, () => {
      prepareObj.authSequence = '';
      scopeOptions.forEach(opt => {
        prepareObj[opt] = !this.checkOptionDisabled(opt);
      });
      this.setState({
        prepareObj,
        visible: true,
      })
    });
  };

  confirmUserChange = (value, index, userIndex, attr) => {
    let {vendorObj} = this.state;
    let arr = vendorObj.commonAgencyAuthDTOS[index].commonAgencyAuthDetailDTOS;
    if(!value || !value.length){
      vendorObj.commonAgencyAuthDTOS[index].commonAgencyAuthDetailDTOS[userIndex][attr] = '';
      if(attr === 'confirmUser') {
        vendorObj.commonAgencyAuthDTOS[index].commonAgencyAuthDetailDTOS[userIndex].confirmUserOID = null;
      }
      if(attr === 'confirmCCUser') {
        vendorObj.commonAgencyAuthDTOS[index].commonAgencyAuthDetailDTOS[userIndex].confirmCCUserOID = null;
      }
      this.setState({
        vendorObj
      });
      return
    }
    if(!arr || !arr.length){
      vendorObj.commonAgencyAuthDTOS[index].commonAgencyAuthDetailDTOS = [{},{},{},{}];
    }
    if(arr && arr.length < 4){
      vendorObj.commonAgencyAuthDTOS[index].commonAgencyAuthDetailDTOS = arr.concat([{},{},{},{}]).slice(0, 4);
    }
    if(attr === 'confirmUser') {
      vendorObj.commonAgencyAuthDTOS[index].commonAgencyAuthDetailDTOS[userIndex].confirmUserOID = value[0].userOID;
    }
    if(attr === 'confirmCCUser') {
      vendorObj.commonAgencyAuthDTOS[index].commonAgencyAuthDetailDTOS[userIndex].confirmCCUserOID = value[0].userOID;
    }
    vendorObj.commonAgencyAuthDTOS[index].commonAgencyAuthDetailDTOS[userIndex][attr] = value[0];
    this.setState({
      vendorObj
    })
  };

  agencyBookListChange = (value) => {
    let {vendorObj} = this.state;
    vendorObj.agencyBookList = value;
    vendorObj.agencyBookUserOIDList = value.map(item => item.userOID);
    this.setState({
      vendorObj
    });
  };

  onCancelEdit = () => {
    this.reset();
    this.props.cancelEdit();
  };

  render () {
    const {getFieldDecorator} = this.props.form;
    const {ctripList, helpOthersBookCodeList, bookTheScopeCodeList, vendorObj, visible, prepareObj, isNew, saveLoading} = this.state;
    let {isEditing} = this.props;
    return (
      <div className='common-consumer-container'>
        <div className='consumer-table-width'>
          <Form>
            <Row>
              <Col span={8}>
                <FormItem {...formItemLayout} label={messages('basic-5.key861')/*子账户*/}>
                  {getFieldDecorator('subAccountCode', {
                    initialValue: vendorObj.subAccountCode ? {key: vendorObj.subAccountCode, label: vendorObj.subAccountName} : undefined,
                  })(
                    <Select
                      disabled={!isEditing}
                      allowClear
                      showSearch
                      labelInValue
                      placeholder={messages('common.select')/*请选择*/}
                      optionFilterProp="children"
                      filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                    >
                      {
                        this.renderCtripAccountOption(ctripList)
                      }
                    </Select>
                  )
                  }
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem {...formItemLayout} label={messages('basic-5.key862')/*标签仓位屏蔽*/}>
                  {getFieldDecorator('positionShield', {
                    initialValue: vendorObj.positionShield,
                  })(
                    <Select disabled={!isEditing} allowClear>
                      <Option value={'Y'}>{messages('common.yes')/*是*/}</Option>
                      <Option value={'N'}>{messages('common.no')/*否*/}</Option>
                    </Select>
                  )
                  }
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem {...formItemLayout} label={messages('basic-5.key431')/*授权密码*/}>
                  {getFieldDecorator('confirmPassword', {
                    initialValue: vendorObj.confirmPassword,
                    rules: [
                      {
                        max: 20,
                        message: messages('basic-5.key378')/*最多输入20个字符*/
                      },
                    ]
                  })(
                    <Input placeholder={messages('common.please.input')/*请输入*/} disabled={!isEditing} />)
                  }
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={8}>
                <FormItem {...formItemLayout} label={messages('basic-5.key437')/*代订类型*/}>
                  {getFieldDecorator('helpOthersBookCode', {
                    initialValue: vendorObj.helpOthersBookCode ? {key: vendorObj.helpOthersBookCode, label: vendorObj.helpOthersBookName} : undefined,
                  })(
                    <Select
                      showSearch
                      allowClear
                      labelInValue
                      disabled={!isEditing}
                      placeholder={messages('common.select')/*请选择*/}
                      optionFilterProp="children"
                      filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                    >
                      {
                        this.renderCtripAccountOption(helpOthersBookCodeList)
                      }
                    </Select>
                  )
                  }
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem {...formItemLayout} label={messages('basic-5.key438')/*代订范围*/}>
                  {getFieldDecorator('bookTheScopeCode', {
                    initialValue: vendorObj.bookTheScopeCode ? {key: vendorObj.bookTheScopeCode, label: vendorObj.bookTheScopeName} : undefined,
                  })(
                    <Select
                      showSearch
                      allowClear
                      labelInValue
                      disabled={!isEditing}
                      onChange={this.bookTheScopeNameChange}
                      placeholder={messages('common.select')/*请选择*/}
                      optionFilterProp="children"
                      filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                    >
                      {
                        this.renderCtripAccountOption(bookTheScopeCodeList)
                      }
                    </Select>
                  )
                  }
                  <div>
                    <Checkbox checked={vendorObj.nonEmployeeIncluded} disabled={!isEditing}  onChange={this.onCheckBoxChange}>
                      {messages('basic-5.key864')/*包括非员工*/}
                    </Checkbox>
                  </div>
                </FormItem>
              </Col>
              <Col span={8}>
                {this.props.form.getFieldValue('bookTheScopeCode') &&
                this.props.form.getFieldValue('bookTheScopeCode').key === "O" &&
                <FormItem {...formItemLayout} label={messages('basic-5.key439')/*具体代订名单*/}>
                  <Chooser single={false}
                           labelKey="fullName"
                           valueKey="userOID"
                           placeholder={messages('common.select')/*请选择*/}
                           disabled={!isEditing}
                           value={vendorObj.agencyBookList || []}
                           onChange={this.agencyBookListChange}
                           type="user"/>
                </FormItem>
                }
              </Col>
            </Row>
          </Form>
        </div>
        <div className='bottom-gap'>
          <Button type='primary' onClick={this.handleNew} disabled={!isEditing}>{messages('basic-5.key865')/*新增服务范围*/}</Button>
        </div>
        <div className='consumer-table consumer-table-width'>
          <div className='common-consumer-table-content common-consumer-table-header consumer-border-bottom'>
            <div className='text-ellipsis common-consumer-table common-consumer-table-narrow'>
              <Popover content={messages('basic-5.key866')/*授权序号*/}>{messages('basic-5.key866')/*授权序号*/}</Popover>
            </div>
            <div className='text-ellipsis common-consumer-table common-consumer-table-vast'>
              <Popover content={messages('basic-5.key867')/*授权服务范围*/}>{messages('basic-5.key867')/*授权服务范围*/}</Popover>
            </div>
            <div className='text-ellipsis common-consumer-table common-consumer-table-narrow'>
              <Popover content={messages('basic-5.key868')/*审核顺序*/}>{messages('basic-5.key868')/*审核顺序*/}</Popover>
            </div>
            <div className='text-ellipsis common-consumer-table common-consumer-table-vast'>
              <Popover content={messages('basic-5.key432')/*授权人*/}>{messages('basic-5.key432')/*授权人*/}</Popover>
            </div>
            <div className='text-ellipsis common-consumer-table common-consumer-table-vast'>
              <Popover content={messages('basic-5.key869')/*抄送人*/}>{messages('basic-5.key869')/*抄送人*/}</Popover>
            </div>
            <div className='text-ellipsis grow-up common-consumer-table'>{messages('common.operation')/*操作*/}</div>
        </div>
        {
          vendorObj.commonAgencyAuthDTOS && vendorObj.commonAgencyAuthDTOS.length ?
            vendorObj.commonAgencyAuthDTOS.map((item, index) => {
              return(
                <div className='common-consumer-table-content consumer-border-bottom text-center' key={item.id}>
                  <div className='common-consumer-table-narrow common-consumer-content operation-bottom'>{item.authSequence}</div>
                  <div className='common-consumer-table-vast common-consumer-content operation-bottom'>
                    <div>
                    {
                      Object.keys(item).map(scope => {
                        if(item[scope]){
                          return <div key={scope}>{scopeOptionMap[scope]}</div>
                        }
                      })
                    }
                  </div>
                  </div>
                  <div className='common-consumer-content consumer-user-wrap'>
                    {
                      (item.commonAgencyAuthDetailDTOS || []).map((user, userIndex) => {
                        return(
                          <div className='common-consumer-table-content consumer-border-bottom' key={user.checkSequence}>
                            <div className='common-consumer-table-narrow consumer-padding-side'>{item.checkSequence || userIndex + 1}</div>
                            <div className='common-consumer-table-vast consumer-padding-side text-left'>
                              <Chooser key={user.id}
                                       single={true}
                                       labelKey="fullName"
                                       placeholder={messages('common.select')/*请选择*/}
                                       valueKey="userOID"
                                       type="user"
                                       disabled={!isEditing}
                                       onChange={(value) =>this.confirmUserChange(value, index, userIndex, 'confirmUser')}
                                       value={user.confirmUser && user.confirmUser.userOID ? [{userOID: user.confirmUser.userOID, fullName: user.confirmUser.fullName}] : []}
                              />
                            </div>
                            <div className='common-consumer-table-vast consumer-padding-side text-left'>
                              <Chooser single={true}
                                       labelKey="fullName"
                                       placeholder={messages('common.select')/*请选择*/}
                                       valueKey="userOID"
                                       type="user"
                                       disabled={!isEditing}
                                       onChange={(value) =>this.confirmUserChange(value, index, userIndex, 'confirmCCUser')}
                                       value={user.confirmCCUser && user.confirmCCUser.userOID ? [{userOID: user.confirmCCUser.userOID, fullName: user.confirmCCUser.fullName}] : []}
                              />
                            </div>
                          </div>
                        )
                      })
                    }
                  </div>
                  <div className='common-consumer-content operation-bottom grow-up'>
                    {
                      isEditing &&
                      <div>
                        <div onClick={(e) => this.handleEdit(e, item, index)} className='bottom-gap'>
                          <a>{messages('basic-5.key870')/*编辑服务范围*/}</a></div>
                        <div onClick={(e) => this.handleDelete(e, item, index)}>
                          <a>{item.deleteLoading ? <Icon type='loading'/> : messages('common.delete')/*删除*/}</a>
                        </div>
                      </div>
                      }
                   </div>
                </div>
              )
            })
            :
            <div className='text-center common-consumer-table-empty consumer-border-bottom'>{messages('common.empty.text')/*暂无数据*/}</div>
        }
        </div>
        {
          isEditing &&
          <div className='inline-gap'>
            <Button type='primary'
                    className='right-gap'
                    loading={saveLoading}
                    onClick={this.saveCommonConsumer}>{messages('common.save')/*保存*/}</Button>
            <Button onClick={this.onCancelEdit}>{messages('common.cancel')/*取消*/}</Button>
          </div>
        }
        <Modal title={isNew ? messages('basic-5.key865')/*新增服务范围*/ : messages('basic-5.key870')/*编辑服务范围*/}
               visible={visible}
               onCancel={() => {this.setState({visible: false})}}
               onOk={this.onModalOk}
        >
          <Form>
            <FormItem {...formItemLayout} label={ <span className='add-service-label'>{messages('basic-5.key866')/*授权序号*/}<span className='required-star'>&nbsp;*&nbsp;</span></span>}>
              <InputNumber min={1}
                           max={9999}
                           step={1}
                           precision={0}
                           disabled={false}
                           onChange={this.onValueChange}
                           value={prepareObj.authSequence}
                           style={{width: 300}}
                           placeholder={messages('basic-5.key871')/*请输入1～9999*/}/>
            </FormItem>
            <FormItem {...formItemLayout} label={<span className='add-service-label'>{messages('basic-5.key867')/*授权服务范围*/}<span className='required-star'>&nbsp;*&nbsp;</span></span>}>
              {
                scopeOptions.map((opt, index) => {
                  return(
                    <span>
                      <Checkbox
                        key={opt}
                        checked={prepareObj[opt]}
                        disabled={this.checkOptionDisabled(opt)}
                        onChange={(e) => this.onAuthScopeChange(e, opt)}>
                      {scopeOptionMap[opt]}
                    </Checkbox>
                    </span>
                  )
                })
              }
            </FormItem>
          </Form>
        </Modal>
      </div>
    )
  }
}

CommonConsumer.propTypes = {
  vendorObj: React.PropTypes.object,//基础信息数据对象
};
CommonConsumer.defaultProps = {
  vendorObj: {},
};
const WrappedPersonVendorInfo = Form.create()(CommonConsumer);
export default WrappedPersonVendorInfo;
